package com.sinoglobal.ningxia.activity.shop;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.view.listener.AbOnListViewListener;
import com.ab.view.pullview.AbPullGridView;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.IBase;
import com.sinoglobal.ningxia.activity.base.BaseActivity;
import com.sinoglobal.ningxia.activity.vip.Login;
import com.sinoglobal.ningxia.adapter.ShoppingGridAdapter;
import com.sinoglobal.ningxia.adapter.ShoppingPagerAdapter;
import com.sinoglobal.ningxia.beans.ShallShopIndexActivityVo;
import com.sinoglobal.ningxia.beans.ShallShopIndexDataVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.TextUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author zbl
 * @createdate 2014-6-24 上午10:26:13
 * @Description:左侧菜单栏点击“精品商城”进入此页面
 */
public class MallShopActivity extends BaseActivity implements IBase, OnPageChangeListener, OnClickListener, AbOnListViewListener {
	private ImageView mallShopBack;// 返回按钮
	private RelativeLayout mallShopMyCoupons;// “我的”
	private LinearLayout secBar;// 现金购买or积分兑换的布局
	private ViewPager goodsViewPager;// 展示商品
	private ShoppingPagerAdapter adapter;// 精品商城中首页Viewpager的adapter
	private TextView[] secTexts;// 现金购买or积分兑换
	private List<View> list = new ArrayList<View>();
	private View cashView, scoreView;
	private AbPullGridView cashGoodsGrid, scoreGoodsGrid;//
	private Intent intent;
	private ShoppingGridAdapter cashGridAdapter, scoreGridAdapter;// 精品商城中商品的adapter
	private ArrayList<ShallShopIndexDataVo> cashDataVo;// 现金购买的数据
	private ArrayList<ShallShopIndexDataVo> scoreDataVo;// 积分兑换的数据
	private TextView userScore;// 积分总数
	private TextView continuous;// 连续登陆时间
	private int pageNumcash = 0;// 现金列表页数
	private int pageNumscore = 0;// 积分列表页数
	private String type;// 商品类型，1.现金 2.积分
	private final String CASH = "1";
	private final String SCORE = "2";
	private final String SCORE_STRING = "score";// score字符串常量
	private RelativeLayout cashNoGoods, scoreNoGoods;// 无数据展示

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isTemplate = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mallshop_view);
		openChenJInShi();//开启沉浸式
		loadInfo(CASH, pageNumcash, true);// 访问网路获取现金购买数据
		loadInfo(SCORE, pageNumscore, false);// 访问网络获取积分兑换数据
		init();// 初始化组件
		// 获取用户登录的天数和枸杞果数
		showListener();
		secTexts[0].setEnabled(false);

	}

	public void init() {
		mallShopBack = (ImageView) findViewById(R.id.mallshop_back);
		mallShopMyCoupons = (RelativeLayout) findViewById(R.id.mycoupons_bar);
		goodsViewPager = (ViewPager) findViewById(R.id.goods_vpager);
		secBar = (LinearLayout) findViewById(R.id.sec_bar);
		userScore = (TextView) findViewById(R.id.mallshop_scores_content);
		continuous = (TextView) findViewById(R.id.mallshop_days_content);

		mallShopBack.setOnClickListener(this);
		mallShopMyCoupons.setOnClickListener(this);

		cashView = LayoutInflater.from(this).inflate(R.layout.mallshop_viewpager_grid, null);
		scoreView = LayoutInflater.from(this).inflate(R.layout.mallshop_viewpager_grid, null);
		cashNoGoods = (RelativeLayout) cashView.findViewById(R.id.no_goods);
		scoreNoGoods = (RelativeLayout) scoreView.findViewById(R.id.no_goods);
		list.add(cashView);
		list.add(scoreView);
		adapter = new ShoppingPagerAdapter(list);
		goodsViewPager.setAdapter(adapter);
		goodsViewPager.setOnPageChangeListener(this);

		secTexts = new TextView[secBar.getChildCount()];
		for (int i = 0; i < secTexts.length; i++) {
			secTexts[i] = (TextView) secBar.getChildAt(i);
			secTexts[i].setOnClickListener(this);
		}

		goodsViewPager.setCurrentItem(0);// 让viewpager显示在第一个页面并激活第一个标题
		cashGoodsGrid = (AbPullGridView) cashView.findViewById(R.id.goods_grid);
		scoreGoodsGrid = (AbPullGridView) scoreView.findViewById(R.id.goods_grid);

		cashDataVo = new ArrayList<ShallShopIndexDataVo>();
		scoreDataVo = new ArrayList<ShallShopIndexDataVo>();
		cashGridAdapter = new ShoppingGridAdapter(this, cashDataVo, CASH);
		scoreGridAdapter = new ShoppingGridAdapter(this, scoreDataVo, SCORE);
		cashGoodsGrid.setAdapter(cashGridAdapter);
		scoreGoodsGrid.setAdapter(scoreGridAdapter);
		// 设置上拉加载和下拉刷新
		cashGoodsGrid.setPullLoadEnable(true);
		cashGoodsGrid.setPullRefreshEnable(false);
		scoreGoodsGrid.setPullLoadEnable(true);
		scoreGoodsGrid.setPullRefreshEnable(false);
		type = "1";

		// 用来设置AndBase AbPullListView 的下拉和加载更多样式
		cashGoodsGrid.getHeaderView().setHeaderProgressBarDrawable(this.getResources().getDrawable(R.drawable.progress_circular));
		cashGoodsGrid.getFooterView().setFooterProgressBarDrawable(this.getResources().getDrawable(R.drawable.progress_circular));
		scoreGoodsGrid.getHeaderView().setHeaderProgressBarDrawable(this.getResources().getDrawable(R.drawable.progress_circular));
		scoreGoodsGrid.getFooterView().setFooterProgressBarDrawable(this.getResources().getDrawable(R.drawable.progress_circular));
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// Auto-generated method stub

		if (data != null) {
			if (TextUtil.stringIsNotNull(data.getStringExtra(SCORE_STRING))) {
				// 支付返回成功时更新积分
				SharedPreferenceUtil.saveString(FlyApplication.context, SCORE_STRING, data.getStringExtra(SCORE_STRING));
				if (TextUtil.stringIsNotNull(data.getStringExtra(SCORE_STRING))) {
					userScore.setText(data.getStringExtra(SCORE_STRING));
				}
			}
		}

		if (Code.CODE_SUCCESS == resultCode) {
			String score = SharedPreferenceUtil.getString(FlyApplication.context, SCORE_STRING);
			userScore.setText(score);
			String days = SharedPreferenceUtil.getString(FlyApplication.context, "signCount");
			continuous.setText(days);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 
	 * @author zbl
	 * @createdate 2014-6-27 上午9:28:22
	 * @Description: 从服务器上加载数据
	 * @param type
	 *            :1.现金 2.积分
	 * @param page
	 *            :请求第几页
	 * @param itit
	 *            :是否显示对话框
	 * 
	 */
	private void loadInfo(final String type, int page, boolean itit) {
		new ItktAsyncTaskWithDialog<Integer, Void, ShallShopIndexActivityVo>(getString(R.string.loading), itit, true) {
			@Override
			public ShallShopIndexActivityVo before(Integer... params) throws Exception {
				return RemoteImpl.getInstance().getIndexActivityVo(type, params[0]);
			}

			@Override
			public void after(ShallShopIndexActivityVo result) {
				cashGoodsGrid.stopLoadMore();
				scoreGoodsGrid.stopLoadMore();
				if (null == result) {
					return;
				}
				if (Code.CODE_SUCCESS == result.getCode()) {

					if (CASH.equals(type)) {
						// 现金购买时加载信息
						cashNoGoods.setVisibility(View.GONE);
						cashGoodsGrid.setPullLoadEnable(true);
						if (!result.getList().isEmpty()) {
							cashDataVo.addAll(result.getList());
							cashGridAdapter.setData(cashDataVo);
							cashGridAdapter.notifyDataSetChanged();
						} else {
							cashNoGoods.setVisibility(View.VISIBLE);
						}
					} else if (SCORE.equals(type)) {//积分兑换
						scoreNoGoods.setVisibility(View.GONE);
						scoreGoodsGrid.setPullLoadEnable(true);
						if (!result.getList().isEmpty()) {
							scoreDataVo.addAll(result.getList());
							scoreGridAdapter.setData(scoreDataVo);
							scoreGridAdapter.notifyDataSetChanged();
						} else {
							scoreNoGoods.setVisibility(View.VISIBLE);
						}

					}

				} else {
					if (CASH.equals(type)) {
						scoreGoodsGrid.setPullLoadEnable(true);
						cashGoodsGrid.setPullLoadEnable(false);
						if (!cashDataVo.isEmpty()) {
							showShortToastMessage(getString(R.string.noMoreMessage));
						} else {
							cashGoodsGrid.setVisibility(View.GONE);
							cashNoGoods.setVisibility(View.VISIBLE);
							if (!scoreDataVo.isEmpty()) {
								scoreNoGoods.setVisibility(View.GONE);
							} else {
								scoreGoodsGrid.setVisibility(View.GONE);
								scoreNoGoods.setVisibility(View.VISIBLE);
							}
						}

					} else {
						cashGoodsGrid.setPullLoadEnable(true);
						scoreGoodsGrid.setPullLoadEnable(false);
						if (!scoreDataVo.isEmpty()) {
							showShortToastMessage(getString(R.string.noMoreMessage));
						} else {
							scoreGoodsGrid.setVisibility(View.GONE);
							scoreNoGoods.setVisibility(View.VISIBLE);
							if (!cashDataVo.isEmpty()) {
								cashNoGoods.setVisibility(View.GONE);
							} else {
								cashGoodsGrid.setVisibility(View.GONE);
								cashNoGoods.setVisibility(View.VISIBLE);
							}
						}

					}

					scoreGoodsGrid.stopLoadMore();
					cashGoodsGrid.stopLoadMore();

				}

				userScore.setText(result.getUser_score());
				continuous.setText(result.getContinuous());
				// 保存当前的积分和登陆天数
				SharedPreferenceUtil.saveString(FlyApplication.context, SCORE_STRING, result.getUser_score());
				SharedPreferenceUtil.saveString(FlyApplication.context, "signCount", result.getContinuous());
			}

			@Override
			public void exception() {

			}

		}.execute(page);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.mall_shop, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// 判断是否是当前点击的view
		for (int i = 0; i < secTexts.length; i++) {
			if (v == secTexts[i]) {
				for (TextView t : secTexts) {
					t.setEnabled(true);

				}
				secTexts[i].setEnabled(false);
				goodsViewPager.setCurrentItem(i);
			}

		}

		switch (v.getId()) {
		case R.id.mallshop_back:
			// 返回上级页面
			finish();
			break;

		case R.id.mycoupons_bar:
			// 判断用户是否登录，若登录则 跳转到“我的”
			if (TextUtil.stringIsNotNull(FlyApplication.userId)) {
				intent = new Intent(this, MyCouponsActivity.class);
				startActivity(intent);
			} else {
				intent = new Intent(this, Login.class);
				startActivityForResult(intent, 0);
			}
			break;

		}

	}

	public void toast(String text) {
		Toast toast = Toast.makeText(FlyApplication.context, text, Toast.LENGTH_SHORT);
		toast.show();
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

		if (goodsViewPager.getCurrentItem() == 0) {
			type = CASH;
		} else {
			type = SCORE;
		}
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int arg0) {

		for (int i = 0; i < secTexts.length; i++) {
			if (secTexts[arg0] == secTexts[i]) {// 当这个ViewPager改变的时候,viewpager被选中
				// 就改变对应标题的状态
				for (TextView t : secTexts) {
					t.setEnabled(true);
				}
				secTexts[i].setEnabled(false);
			}
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onRefresh() {
	}

	@Override
	public void onLoadMore() {
		if (goodsViewPager.getCurrentItem() == 0) {
			loadInfo(type, ++pageNumcash, false); // 现金列表加载更多
		} else {
			loadInfo(type, ++pageNumscore, false);// 积分列表加载更多
		}
	}

	@Override
	public void showListener() {
		cashGoodsGrid.setAbOnListViewListener(this);
		scoreGoodsGrid.setAbOnListViewListener(this);

	}

}
